package repository

import (
	v1 "server_go/api/v1"
	"server_go/internal/model"
)

type FileRepository interface {
	UploadFile(file *model.File) (int64, error)
	DeleteFile(fileId int64) error
	GetFileById(fileId int64) (*model.File, error)
}

func NewFileRepository(
	repository *Repository,
) FileRepository {
	return &fileRepository{
		Repository: repository,
	}
}

type fileRepository struct {
	*Repository
}

func (r *fileRepository) UploadFile(file *model.File) (int64, error) {
	// 插入path和 name 和 type
	if err := r.db.Table("file").Create(&file).Error; err != nil {
		return 0, err
	}
	return int64(file.ID), nil
}

func (r *fileRepository) DeleteFile(fileId int64) error {
	if err := r.db.Table("file").Delete(&model.File{}, fileId).Error; err != nil {
		return err
	}
	return nil
}

func (r *fileRepository) GetFileById(fileId int64) (*model.File, error) {
	var count int64
	if err := r.db.Table("file").
		Where("id = ? AND deleted_at IS NULL", fileId).
		Count(&count).Error; err != nil {
		return nil, err
	}
	if count == 0 {
		return nil, v1.ErrFileNotExist
	}
	var file *model.File
	if err := r.db.Table("file").Where("id = ?", fileId).First(&file).Error; err != nil {
		return nil, err
	}
	return file, nil
}
